package shichenyang;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 就是一个获取网页信息的小例子，就是不知道如果到了VIP章节的时候会是什么情况
 * @author shichenyang
 */
public class Formal {
	private static String startUrl="http://read.qidian.com/chapter/ksAQlR5QWftRGoWu-UQg7Q2/0QnuPWghqKHgn4SMoDUcDQ2";
	private String className="read-content j_readContent";
	private String classNameTwo="j_chapterName";
	private String id="j_chapterNext";
	private static String dicName="D:\\WuShi";
	/**
	 * 开始执行的方法，也没有提示
	 * @param args
	 */
	public static void main(String[] args) {
		Formal formal=new Formal();
		String url=startUrl;
		int i=1;
		try {
			url=formal.get(url);
			while (i==1) {
				try {
					url=formal.get("http:"+url);
				} catch (Exception e) {
					i=2;
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 去网页获取信息
	 * @param url 网页的url
	 * @return 返回下一章的url
	 * @throws IOException 
	 */
	public String get(String url) throws IOException{
		//1.建立连接
		Connection connection = Jsoup.connect(url).ignoreContentType(true);
		//2.网页返回内容
		Response response = connection.execute();
		//3.加载网页内容信息
		Document document = Jsoup.parse(response.body());
		//4.获取章节名称
		String fileName=document.getElementsByClass(classNameTwo).get(0).text();
		//5.所有的内容信息
		Elements elements = document.getElementsByClass(className);
		//6.生成TXT
		createFile(elements,fileName);
		//7.下一章的URL
		Element elementId = document.getElementById(id);
		return elementId.attr("href");
	}
	/**
	 * 创建文件，暂时就给TXT吧
	 * @param elements 章节内容
	 * @param fileName 章节名
	 */
	public void createFile(Elements elements,String fileName){
		FileWriter fw = null;
		try {
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File("D:\\Wushi\\"+fileName+".txt");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		for (Element element : elements.get(0).children()) {
			pw.println(element.text());
		}
		System.out.println("打印"+fileName);
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
